#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>

int main(void)
{
    int server_sockfd, client_sockfd;
    int server_len, client_len;
    struct sockaddr_in server_address;
    struct sockaddr_in client_address;

    server_sockfd = socket(AF_INET, SOCK_STREAM, 0);

    server_address.sin_family = AF_INET;
    //注意：inet_addr返回的已经是按照网络字节序存储的网络地址了，所以不能再加htonl了
    server_address.sin_addr.s_addr = inet_addr("192.168.33.205");
    server_address.sin_port = htons(11021);
    server_len = sizeof(server_address);
    bind(server_sockfd, (struct sockaddr*)&server_address, server_len);

    listen(server_sockfd, 5);
    printf("server waiting\n");

    client_len = sizeof(client_address);
    client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_address, &client_len);

    printf("client connected.\n");

    //server不发、client不收，recv返回0，不会出现"connect reset by peer"错误
    send(client_sockfd, "hello world", strlen("hello world"), 0);

    char str[1024] = {0};
    int len = recv(client_sockfd, str, 1023, 0);
    //recv换成read，同样的效果
    //int len = read(client_sockfd, str, 1023);
    printf("recv len = %d\n", len);
    if (len == -1)
    {
        perror("recv: ");
    }

    printf("server end!!!!\n");

    return 0;
}
